﻿using OA.BLL;

using OA.Core;
using OA.Model;
using OA.Model.View;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

using Z.EntityFramework.Plus;
using Microsoft.Extensions.Caching.Memory;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using OA.Web.Attribute;
using Microsoft.AspNetCore.Mvc;
using X.PagedList;
using OA.Core.Helper;
using OA.Model.DB;
using OA.Core.EF;

namespace OA.Web.Areas.Member.Controllers
{
    public class SynergyController : BaseMemberController
    {

        private IMemoryCache _cache;
        private ICookie _cookie;
        public SynergyController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
            _cookie = cookie;
        }

        [MyActionFilter("000002", "办公协作", "后台首页", true, "iconjiedai")]
        public IActionResult Index()
        {
            return View();
        }

        [MyActionFilter("000002", "办公协作")]
        public IActionResult GetData(string keywrod, int page = 1, int limit = 20)
        {
            Expression<Func<SynergyForm, bool>> where = m => m.Status >= 0 && m.EmpID == EmpID || m.SynergyEmpID.Contains("," + EmpID + ",");
            if (!string.IsNullOrEmpty(keywrod))
            {
                where = where.AndAlso<SynergyForm>(m => m.Name.Contains(keywrod));
            }

            var list = this.dbContextFactory.DbContext.SynergyForm.Where(where).OrderByDescending(m => m.ID).Select(SimpleSynergyForm.Map).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);
        }


        [HttpGet]
        public IActionResult Add()
        {
            SynergyForm model = new SynergyForm();

            model.ListExtendField = new List<ExtendField>() {
                new ExtendField()
            };

            model.TableFields = new List<ExtendField>() {
                new ExtendField()
            };

            model.SynergyEmployees
                 = new List<CountersignEmployee>() {
                new CountersignEmployee()
            };
            return View(model);

        }

        [HttpPost]
        public IActionResult Add(SynergyForm model)
        {
            BaseResult baseResult = new BaseResult();
            try
            {
                model.EmpID = this.EmpID;
                model.EmpName = this.Info.EmpName;
                model.Status = 0;
                model.CreateDateTime = DateTime.Now;
                #region 协作成员
                if (model.SynergyEmployees == null)
                {
                    model.SynergyEmployees = new List<CountersignEmployee>();
                }
                model.SynergyEmployees = model.SynergyEmployees.Where(m => m.Status != -1).ToList();
                List<CountersignEmployee> mySynergyEmployees = new List<CountersignEmployee>();
                foreach (CountersignEmployee item in model.SynergyEmployees)
                {
                    if (mySynergyEmployees.Where(m => m.EmpID == item.EmpID).Count() == 0)
                    {
                        mySynergyEmployees.Add(item);
                    }
                }
                model.SynergyEmployeesContent = JsonConvert.SerializeObject(mySynergyEmployees);
                model.SynergyEmpID = "," + string.Join(",", mySynergyEmployees.Select(m => m.EmpID).ToList()) + ",";
                #endregion

                CustomFormExtendInfo extendInfo = new CustomFormExtendInfo();
                extendInfo.ListExtendField = model.ListExtendField.Where(m => m.Status != -1 && !string.IsNullOrWhiteSpace(m.Name)).OrderBy(m => m.Sort).ToList();
                string chars = "qwertyuiopasdfghjklmnbvcxz";
                int index = 0;
                foreach (ExtendField item in extendInfo.ListExtendField)
                {
                    index++;
                    if (!item.Attribute.StartsWith("_"))
                    {
                        item.Attribute = "_" + item.Attribute;
                    }
                    else
                    {
                        while (item.Attribute.StartsWith("__"))
                        {
                            item.Attribute = item.Attribute.Substring(1);
                        }
                        if (item.Attribute.Length <= 1)//_,a
                        {
                            if (item.Attribute.StartsWith("_"))
                            {
                                item.Attribute = "_" + chars[index % 26] + CommonHelper.GetRandom();
                            }
                            else
                            {
                                item.Attribute = "_" + item.Attribute;
                            }

                        }
                    }
                }
                extendInfo.TableFields = model.TableFields.Where(m => m.Status != -1 && !string.IsNullOrWhiteSpace(m.Name)).OrderBy(m => m.Sort).ToList();
                foreach (ExtendField item in extendInfo.TableFields)
                {
                    index++;
                    if (!item.Attribute.StartsWith("__"))
                    {
                        if (item.Attribute.StartsWith("_"))
                        {
                            item.Attribute = "_" + item.Attribute;
                        }
                        else
                        {
                            item.Attribute = "__" + item.Attribute;
                        }
                    }
                    else
                    {
                        while (item.Attribute.StartsWith("___"))
                        {
                            item.Attribute = item.Attribute.Substring(1);
                        }

                        if (item.Attribute.Length <= 2)//_,__,_a,__a
                        {
                            if (item.Attribute == "_" || item.Attribute == "__")
                            {
                                item.Attribute = "__" + chars[index % 26] + CommonHelper.GetRandom();
                            }
                            else
                            {
                                item.Attribute = "_" + item.Attribute;
                            }
                        }

                    }
                }
                model.ExtendField = JsonConvert.SerializeObject(extendInfo);
                this.dbContextFactory.DbContext.SynergyForm.Add(model);
                this.dbContextFactory.DbContext.SaveChanges();
                baseResult.Msg = "添加成功";
            }
            catch(Exception ex)
            {
                baseResult.State = 400;
                baseResult.Msg = ex.Message;
            }
            return Json(baseResult);

        }


        [HttpGet]
        public IActionResult Edit(int id)
        {
            SynergyForm info = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).FirstOrDefault();
            if(info == null|| info.EmpID!=this.EmpID)
            {
                return Redirect("/Area/Member/Home/ShowInfo?msg=" + HttpUtility.UrlEncode("没有找到相关协作!"));
            }

            CustomFormExtendInfo extendInfo = null;
            if (!string.IsNullOrWhiteSpace(info.ExtendField))
            {
                extendInfo = JsonHelper.DeserializeObj<CustomFormExtendInfo>(info.ExtendField);
            }

            if (extendInfo == null || extendInfo.ListExtendField == null || extendInfo.ListExtendField.Count == 0)
            {
                info.ListExtendField = new List<ExtendField>() {
                    new ExtendField()
                };
            }
            else
            {
                info.ListExtendField = extendInfo.ListExtendField;
            }

            if (extendInfo == null || extendInfo.TableFields == null || extendInfo.TableFields.Count == 0)
            {
                info.TableFields = new List<ExtendField>() {
                    new ExtendField()
                };
            }
            else
            {
                info.TableFields = extendInfo.TableFields;
            }

            if (string.IsNullOrWhiteSpace(info.SynergyEmployeesContent))
            {
                info.SynergyEmployees = new List<CountersignEmployee>() { new CountersignEmployee() };
            }
            else
            {
                var list = JsonHelper.DeserializeList<CountersignEmployee>(info.SynergyEmployeesContent);
                if (list == null||list.Count==0)
                {
                    info.SynergyEmployees = new List<CountersignEmployee>() { new CountersignEmployee() };
                }
                else
                {
                    CEmployee.AutoCountersignEmployee(list,_cache);
                    info.SynergyEmployees = list;                    
                }
            }


            return View("Add", info);
        }

        [HttpGet]
        public IActionResult Show(int id)
        {
            SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).FirstOrDefault();

            if (!infoSynergyForm.SynergyEmpID.Contains(EmpID) && infoSynergyForm.EmpID != this.EmpID)
            {
                return Redirect($"/Member/Synergy/Index?msg=您没有当前协作文档的编辑权限");
            }

            if (!string.IsNullOrWhiteSpace(infoSynergyForm.CurrentEditor) && infoSynergyForm.CurrentEditor != this.EmpID)
            {
                return Redirect($"/Member/Synergy/Index?msg=当前协作文档的编辑权限已被【{infoSynergyForm.CurrentEditorName}】锁定");
            }

            if (infoSynergyForm.Status == 2)
            {
                return Redirect($"/Member/Synergy/Index?msg=当前协作文档已完成");
            }

            this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).Update(m => new SynergyForm() { CurrentEditor = this.Info.EmpID, CurrentEditorName = this.Info.EmpName });

            CustomFormExtendInfo extendInfo = null;
            if (!string.IsNullOrWhiteSpace(infoSynergyForm.ExtendField))
            {
                extendInfo = JsonHelper.DeserializeObj<CustomFormExtendInfo>(infoSynergyForm.ExtendField);
            }

            if (extendInfo == null)
            {
                extendInfo = new CustomFormExtendInfo();
            }

            ViewBag.CustomFormExtendInfo = extendInfo;

            //ExtensionResultInfo extensionResultInfo = null;
            //if (!string.IsNullOrWhiteSpace(infoSynergyForm.Content))
            //{
            //    extensionResultInfo = JsonHelper.DeserializeObj<ExtensionResultInfo>(infoSynergyForm.Content);
            //}
            //if (extensionResultInfo == null) { extensionResultInfo = new ExtensionResultInfo(); }

            //if (extensionResultInfo.TableValues == null)
            //{
            //    extensionResultInfo.TableValues = new List<Dictionary<string, string>>();
            //}
            //if (extensionResultInfo.DicExtend == null)
            //{
            //    extensionResultInfo.DicExtend = new Dictionary<string, string>();
            //}
            //ViewBag.TableValues = extensionResultInfo.TableValues;
            //ViewBag.DicExtend = extensionResultInfo.DicExtend;

            return View(infoSynergyForm);
        }



        [HttpPost]
        public IActionResult Edit(int id,SynergyForm model)
        {
            BaseResult baseResult = new BaseResult();
            try
            {
                SynergyForm info = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).FirstOrDefault();
                if (info == null || info.EmpID != this.EmpID)
                {
                    baseResult.State = 400;
                    baseResult.Msg = "没有找到相关协作!";
                    return Json(baseResult);
                }
                model.EmpID = this.EmpID;
                model.EmpName = this.Info.EmpName;
                model.Status = 0;
                model.CreateDateTime = DateTime.Now;
                #region 协作成员
                if (model.SynergyEmployees == null)
                {
                    model.SynergyEmployees = new List<CountersignEmployee>();
                }
                model.SynergyEmployees = model.SynergyEmployees.Where(m => m.Status != -1).ToList();
                List<CountersignEmployee> mySynergyEmployees = new List<CountersignEmployee>();
                foreach (CountersignEmployee item in model.SynergyEmployees)
                {
                    if (mySynergyEmployees.Where(m => m.EmpID == item.EmpID).Count() == 0)
                    {
                        mySynergyEmployees.Add(item);
                    }
                }
                model.SynergyEmployeesContent = JsonConvert.SerializeObject(mySynergyEmployees);
                model.SynergyEmpID = "," + string.Join(",", mySynergyEmployees.Select(m => m.EmpID).ToList()) + ",";
                #endregion

                CustomFormExtendInfo extendInfo = new CustomFormExtendInfo();
                extendInfo.ListExtendField = model.ListExtendField.Where(m => m.Status != -1 && !string.IsNullOrWhiteSpace(m.Name)).OrderBy(m => m.Sort).ToList();
                string chars = "qwertyuiopasdfghjklmnbvcxz";
                int index = 0;
                foreach (ExtendField item in extendInfo.ListExtendField)
                {
                    index++;
                    if (!item.Attribute.StartsWith("_"))
                    {
                        item.Attribute = "_" + item.Attribute;
                    }
                    else
                    {
                        while (item.Attribute.StartsWith("__"))
                        {
                            item.Attribute = item.Attribute.Substring(1);
                        }
                        if (item.Attribute.Length <= 1)//_,a
                        {
                            if (item.Attribute.StartsWith("_"))
                            {
                                item.Attribute = "_" + chars[index % 26] + CommonHelper.GetRandom();
                            }
                            else
                            {
                                item.Attribute = "_" + item.Attribute;
                            }

                        }
                    }
                }
                extendInfo.TableFields = model.TableFields.Where(m => m.Status != -1 && !string.IsNullOrWhiteSpace(m.Name)).OrderBy(m => m.Sort).ToList();
                foreach (ExtendField item in extendInfo.TableFields)
                {
                    index++;
                    if (!item.Attribute.StartsWith("__"))
                    {
                        if (item.Attribute.StartsWith("_"))
                        {
                            item.Attribute = "_" + item.Attribute;
                        }
                        else
                        {
                            item.Attribute = "__" + item.Attribute;
                        }
                    }
                    else
                    {
                        while (item.Attribute.StartsWith("___"))
                        {
                            item.Attribute = item.Attribute.Substring(1);
                        }

                        if (item.Attribute.Length <= 2)//_,__,_a,__a
                        {
                            if (item.Attribute == "_" || item.Attribute == "__")
                            {
                                item.Attribute = "__" + chars[index % 26] + CommonHelper.GetRandom();
                            }
                            else
                            {
                                item.Attribute = "_" + item.Attribute;
                            }
                        }

                    }
                }
                model.ExtendField = JsonConvert.SerializeObject(extendInfo);
                this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).Update(m => new SynergyForm() { Name = model.Name, EmpID = model.EmpID, EmpName = model.EmpName, ExtendField = model.ExtendField, SynergyEmpID = model.SynergyEmpID, SynergyEmployeesContent = model.SynergyEmployeesContent });
                this.dbContextFactory.DbContext.SaveChanges();
                baseResult.Msg = "修改成功";
                return Json(baseResult);
            }
            catch(Exception ex)
            {
                baseResult.State = 400;
                baseResult.Msg = ex.Message;
                return Json(baseResult);
            }
            
             

        }


        [HttpGet]
        public IActionResult SponsorItem(int id)
        {
            BaseResult result = new BaseResult();
            SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID && m.Status != -1).FirstOrDefault();
            if(infoSynergyForm==null)
            {
                result.State = 400;
                result.Msg = "没有找到该协作";
            }
            else if(infoSynergyForm.Status>0)
            {
                result.State = 400;
                result.Msg = "该协作已经发起，不需要重复发起";
            }
            this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID).Update(m => new SynergyForm() { Status = 1, LaunchDateTime = DateTime.Now });
            return Json(result);

        }


        [HttpGet]
        public IActionResult Delete(int id)
        {
            BaseResult result = new BaseResult();
            SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID).FirstOrDefault();
            if (infoSynergyForm == null)
            {
                result.State = 400;
                result.Msg = "没有找到该协作";
            }
            else if (infoSynergyForm.Status == 2)
            {
                result.State = 400;
                result.Msg = "已完成的协作，不允许删除";
            }
            this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID).Update(m => new SynergyForm() { Status = -1 });
            return Json(result);

        }


        

        [HttpGet]
        public IActionResult Finish(int id)
        {
            BaseResult result = new BaseResult();
            SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID && m.Status != -1).FirstOrDefault();
            if (infoSynergyForm == null)
            {
                result.State = 400;
                result.Msg = "没有找到该协作";
            }
            else if (infoSynergyForm.Status ==0)
            {
                result.State = 400;
                result.Msg = "不能完结未发起的协作";
            }
            this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID).Update(m => new SynergyForm() { Status = 2, CurrentEditor = "", CurrentEditorName = "" });
            return Json(result);

        }


        [HttpGet]
        public IActionResult ReDo(int id)
        {
            BaseResult result = new BaseResult();
            SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID && m.Status != -1).FirstOrDefault();
            if (infoSynergyForm == null)
            {
                result.State = 400;
                result.Msg = "没有找到该协作";
            }
            this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID).Update(m => new SynergyForm() { Status = 1, CurrentEditor = "", CurrentEditorName = "" });
            return Json(result);

        }

        [HttpGet]
        public IActionResult Unlock(int id)
        {
            BaseResult result = new BaseResult();
            SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.Status != -1).FirstOrDefault();
            if (infoSynergyForm == null)
            {
                result.State = 400;
                result.Msg = "没有找到该协作";
                return Json(result);
            }
            if(infoSynergyForm.CurrentEditor!=this.EmpID&&infoSynergyForm.EmpID!=this.EmpID)
            {
                result.State = 400;
                result.Msg = "您没有解锁权限，只有文档当前编辑者或文档作者才具有解锁权限";
                return Json(result);
            }
            this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).Update(m => new SynergyForm() { Status = 1, CurrentEditor = "", CurrentEditorName = "" });
            return Json(result);

        }

        [HttpGet]
        public IActionResult Clone(int id)
        {
            BaseResult result = new BaseResult();
            SynergyForm model = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id && m.EmpID == EmpID && m.Status != -1).FirstOrDefault();
            if (model == null)
            {
                result.State = 400;
                result.Msg = "没有找到该协作";
            }
            SynergyForm infoSynergyForm = JsonHelper.DeserializeObj<SynergyForm>(JsonHelper.SerializeObject(model));
            infoSynergyForm.ID = 0;
            infoSynergyForm.Content = "";
            infoSynergyForm.CreateDateTime = DateTime.Now;
            infoSynergyForm.CurrentEditor = "";
            infoSynergyForm.CurrentEditorName = "";
            infoSynergyForm.EmpID = this.EmpID;
            infoSynergyForm.EmpName = this.Info.EmpName;
            infoSynergyForm.LaunchDateTime = null;
            infoSynergyForm.SharedMember = "";
            infoSynergyForm.Status = 0;
            infoSynergyForm.Versions = "";
            this.dbContextFactory.DbContext.SynergyForm.Add(infoSynergyForm);
            this.dbContextFactory.DbContext.SaveChanges();
            return Json(result);

        }


        /// <summary>
        /// 协作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Collaboration(int id)
        {
            SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).FirstOrDefault();

            if(!infoSynergyForm.SynergyEmpID.Contains(EmpID)&&infoSynergyForm.EmpID!=this.EmpID)
            {
                return Redirect($"/Member/Synergy/Index?msg=您没有当前协作文档的编辑权限");
            }

            if (!string.IsNullOrWhiteSpace(infoSynergyForm.CurrentEditor)&&infoSynergyForm.CurrentEditor!=this.EmpID)
            {
                return Redirect($"/Member/Synergy/Index?msg=当前协作文档的编辑权限已被【{infoSynergyForm.CurrentEditorName}】锁定");
            }

            if(infoSynergyForm.Status==2)
            {
                return Redirect($"/Member/Synergy/Index?msg=当前协作文档已完成");
            }

            this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).Update(m => new SynergyForm() { CurrentEditor = this.Info.EmpID, CurrentEditorName = this.Info.EmpName });

            CustomFormExtendInfo extendInfo = null;
            if (!string.IsNullOrWhiteSpace(infoSynergyForm.ExtendField))
            {
                extendInfo = JsonHelper.DeserializeObj<CustomFormExtendInfo>(infoSynergyForm.ExtendField);
            }

            if (extendInfo == null)
            {
                extendInfo = new CustomFormExtendInfo();
            }

            ViewBag.CustomFormExtendInfo = extendInfo;

            //ExtensionResultInfo extensionResultInfo = null;
            //if (!string.IsNullOrWhiteSpace(infoSynergyForm.Content))
            //{
            //    extensionResultInfo = JsonHelper.DeserializeObj<ExtensionResultInfo>(infoSynergyForm.Content);
            //}
            //if (extensionResultInfo == null) { extensionResultInfo = new ExtensionResultInfo(); }

            //if (extensionResultInfo.TableValues == null)
            //{
            //    extensionResultInfo.TableValues = new List<Dictionary<string, string>>();
            //}
            //if (extensionResultInfo.DicExtend == null)
            //{
            //    extensionResultInfo.DicExtend = new Dictionary<string, string>();
            //}
            //ViewBag.TableValues = extensionResultInfo.TableValues;
            //ViewBag.DicExtend = extensionResultInfo.DicExtend;

            return View(infoSynergyForm);


        }

        /// <summary>
        /// 协作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Collaboration(int id, TableValues tableValues, Dictionary<string, string> dicExtend)
        {
            BaseResult baseResult = new BaseResult();
            try
            {
                SynergyForm infoSynergyForm = this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).FirstOrDefault();

                if (!infoSynergyForm.SynergyEmpID.Contains(EmpID) && infoSynergyForm.EmpID != this.EmpID)
                {
                    baseResult.State = 400;
                    baseResult.Msg = "您没有当前协作文档的编辑权限";
                    return Json(baseResult);
                }
                if (infoSynergyForm.CurrentEditor != this.EmpID)
                {
                    baseResult.State = 400;
                    baseResult.Msg = "您未分配到当前协作文档的编辑权限";
                    return Json(baseResult);
                }
               // ExtensionResultInfo infoExtension = new ExtensionResultInfo();
                //if (tableValues.RowValues != null)
                //{
                //    tableValues.RowValues = tableValues.RowValues.Where(m => m.Status != -1).ToList();
                //}
                //foreach (var item in tableValues.RowValues)
                //{
                //    infoExtension.TableValues.Add(item.CellValues);
                //}
                
                //infoExtension.DicExtend = dicExtend;
                infoSynergyForm.Status = 1;
                //infoSynergyForm.Content = JsonConvert.SerializeObject(infoExtension);
                List<SynergyFormVersions> synergyFormVersions = new List<SynergyFormVersions>();

                if (!string.IsNullOrWhiteSpace(infoSynergyForm.Versions))
                {
                    synergyFormVersions = JsonHelper.DeserializeList<SynergyFormVersions>(infoSynergyForm.Versions);
                }
                SynergyFormVersions synergyFormVersion = new SynergyFormVersions();
                synergyFormVersion.Editor = this.EmpID;
                synergyFormVersion.EditorName = this.Info.EmpName;
                synergyFormVersion.EditTime = DateTime.Now;
                //synergyFormVersion.ResultInfo = infoExtension;
                synergyFormVersions.Add(synergyFormVersion);
                infoSynergyForm.Versions = JsonHelper.SerializeObject(synergyFormVersions);
                this.dbContextFactory.DbContext.SynergyForm.Where(m => m.ID == id).Update(m => new SynergyForm() { Content = infoSynergyForm.Content, Versions = infoSynergyForm.Versions });
                baseResult.Msg = "文档保存成功";
                return Json(baseResult);
            }
            catch(Exception ex)
            {
                baseResult.State = 400;
                baseResult.Msg = ex.ToString();
            }
            return Json(baseResult);
        }
    }
}